﻿using System;
using System.Collections.Generic;
using Microsoft.Extensions.Caching.Memory;
using TimerTask.Common.Utils;
using TimerTask.Dal;
using TimerTask.Model.Common;
using TimerTask.Model.Entity;
using TimerTask.Service.NotifyTools;

namespace TimerTask.Service
{
    public class AlarmService
    {
        private static Dictionary<int, JobInfo> _notifyDic;

        private static IMemoryCache _memoryCache;

        private static List<INotify> _notifies;

        public static void Alarm(int jobId, bool isSuccessed, string failResult)
        {

            JobInfoDal dal = new JobInfoDal();
            var job = dal.Query(jobId);
            //增加记录：
            foreach (var notify in _notifies)
            {
                if (!isSuccessed)
                {
                    string tmp;
                    //检测NotifyInterval分钟内有没有报警记录，如果没有，则报警；
                    if (!_memoryCache.TryGetValue(job.Id, out tmp))
                    {
                        _memoryCache.Set(job.Id, "1", new MemoryCacheEntryOptions()
                             .SetAbsoluteExpiration(TimeSpan.FromMinutes(AppConfig.Instance.NotifyInterval)));
                        if (!_notifyDic.ContainsKey(job.Id))
                        {
                            _notifyDic.Add(job.Id, job);
                        }
                        //发送失败通知
                        notify.Notify(job, false, failResult);
                    }
                    else
                    {
                        //检测恢复通知，
                        if (!_notifyDic.ContainsKey(job.Id))
                        {
                            _memoryCache.Set(job.Id, "1", new MemoryCacheEntryOptions()
                                .SetAbsoluteExpiration(TimeSpan.FromMinutes(AppConfig.Instance.NotifyInterval)));
                            _notifyDic.Add(job.Id, job);
                            //发送失败通知
                            notify.Notify(job, false, failResult);
                        }
                    }
                }
                else
                {
                    bool removeRes = _notifyDic.Remove(job.Id);
                    if (removeRes)
                    {
                        _memoryCache.Remove(job.Id);
                        //发送恢复通知
                        notify.Notify(job, true, failResult);
                    }
                }
            }

            if (!isSuccessed)
            {
                //增加警告记录
                AlarmLog log = new AlarmLog();
                log.JobId = job.Id;
                log.AlarmTime = DateTime.Now;
                log.Mode = AppConfig.Instance.NotifyMethod;
                log.Result = TriggerStatus.Fail;
                new AlarmLogDal().AddAlarmLog(log);
            }
        }

        private static bool _inited;

        public static void Init()
        {
            if (_inited)
            {
                return;
            }
            _inited = true;
            _notifyDic = new Dictionary<int, JobInfo>();
            _notifies = new List<INotify>();
            _memoryCache = new MemoryCache(new MemoryCacheOptions());

            //Email
            if ((AppConfig.Instance.NotifyMethod & EmailNotify.NotifyCode) > 0)
            {
                _notifies.Add(EmailNotify.Instance());
            }

            //Sms
            if ((AppConfig.Instance.NotifyMethod & SmsNotify.NotifyCode) > 0)
            {
                _notifies.Add(SmsNotify.Instance());
            }
        }
    }
}
